package com.chao.yyks.modular.paragraph.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.chao.common.util.DateUtile;
import com.chao.common.util.ListUtile;
import com.chao.common.util.RequestUtile;
import com.chao.common.util.StrUtile;
import com.chao.common.util.exception.SysException;
import com.chao.common.util.reaction.PageList;
import com.chao.yyks.modular.paragraph.bean.EnParagraph;
import com.chao.yyks.modular.paragraph.mapper.EnParagraphMapper;
import com.chao.yyks.modular.paragraph.service.EnParagraphService;
import com.chao.yyks.modular.problem.bean.EnProblem;
import com.chao.yyks.modular.problem.mapper.EnProblemAnswerMapper;
import com.chao.yyks.modular.problem.mapper.EnProblemMapper;
import com.chao.yyks.modular.score.bean.EnAnswer;
import com.chao.yyks.modular.score.bean.EnScore;
import com.chao.yyks.modular.score.mapper.EnAnswerMapper;
import com.chao.yyks.modular.score.mapper.EnScoreMapper;
import com.chao.yyks.modular.sys.bean.EnClasssType;
import com.chao.yyks.modular.sys.bean.EnStudent;
import com.chao.yyks.modular.sys.mapper.EnClasssTypeMapper;
import com.chao.yyks.modular.sys.mapper.EnStudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 阅读文章ServiceImpl
 * chao
 * 2024-09-12
 */
@Service
public class EnParagraphServiceImpl implements EnParagraphService {

	/**
	 * 阅读文章Mapper
	 */
	@Autowired
	private EnParagraphMapper enParagraphMapper;

	/**
	 * 问题数量配置Mapper
	 */
	@Autowired
	private EnClasssTypeMapper enClasssTypeMapper;

	/**
	 * 学生Mapper
	 */
	@Autowired
	private EnStudentMapper enStudentMapper;

	/**
	 * 成绩Mapper
	 */
	@Autowired
	private EnScoreMapper enScoreMapper;

	/**
	 * 成绩答题Mapper
	 */
	@Autowired
	private EnAnswerMapper enAnswerMapper;

	/**
	 * 问题答案Mapper
	 */
	@Autowired
	private EnProblemAnswerMapper enProblemAnswerMapper;

	/**
	 * 题库Mapper
	 */
	@Autowired
	private EnProblemMapper enProblemMapper;


	/**
	 * 新增阅读文章
	 */
	@Override
	@Transactional
	public void insertEnParagraph(EnParagraph enParagraph){
		enParagraph.setParagraphId(StrUtile.getId());
		enParagraph.setCtime(new Date());
		enParagraphMapper.insertEnParagraph(enParagraph);
	}

	/**
	 * 修改阅读文章
	 */
	@Override
	@Transactional
	public void updateEnParagraph(EnParagraph enParagraph){
		EnParagraph enParagraphPojo = enParagraphMapper.selectEnParagraphByParagraphId(enParagraph.getParagraphId());
		if(null == enParagraphPojo){
		    throw new SysException("修改阅读文章失败:记录不存在!");
		}
		enParagraphMapper.updateEnParagraph(enParagraph);
	}

	/**
	 * 物理删除阅读文章
	 */
	@Override
	@Transactional
	public void deleteDataEnParagraph(String paragraphId){
		EnParagraph enParagraph = enParagraphMapper.selectEnParagraphByParagraphId(paragraphId);
		if(null == enParagraph){
		    throw new SysException("删除阅读文章失败:记录不存在!");
		}
		enParagraphMapper.deleteDataEnParagraph(paragraphId);

		enProblemMapper.deleteDataEnProblem(paragraphId);

		enProblemAnswerMapper.deleteDataEnProblem();

		enProblemAnswerMapper.deleteOpDataEnProblem();
	}

	/**
	 * 查询阅读文章详情
	 */
	@Override
	public EnParagraph selectEnParagraphByParagraphId(String paragraphId){
		return enParagraphMapper.selectEnParagraphByParagraphId(paragraphId);
	}

	/**
	 * 查询阅读文章列表
	 */
	@Override
	public PageList<EnParagraph> selectEnParagraphByList(JSONObject json){
		return enParagraphMapper.selectEnParagraphByList(json);
	}

	/**
	 * 分页查询阅读文章列表
	 */
	@Override
	public PageList<EnParagraph> selectEnParagraphByPage(JSONObject json){
		return enParagraphMapper.selectEnParagraphByList(StrUtile.getPageJson(json));
	}

//	/**
//	 * 词汇题试卷
//	 */
//	@Override
//	public List<EnAnswer> selectEnParagraphCH(JSONObject json){
//		if(json.containsKey("scoreId")){
//			return enAnswerMapper.selectEnAnswerByList(JSONObject.parseObject("{\"scoreId\":\""+json.getString("scoreId")+"\"}")).getList();
//		}
//		json.put("problemDateThis",DateUtile.laseWook());
//		EnStudent enStudent = enStudentMapper.selectEnStudentByStudentId(RequestUtile.getLoginUserId());
//		if(null == enStudent){
//			throw new SysException("登录账号异常,请重新登录或联系老师!");
//		}
//		List<EnClasssType> typeList = enClasssTypeMapper.selectEnClasssTypeByList(enStudent.getClasssId());
//		Map<String,Integer> typeMap = typeList.stream().filter(t->"3".equals(t.getProblemUpType())).collect(Collectors.toMap(EnClasssType::getProblemType,EnClasssType::getProblemNum));
//		if(typeMap.isEmpty()){
//			throw new SysException("当前学生不需要填写词汇题!");
//		}
//		json.put("studentId",enStudent.getStudentId());
//		json.put("problemUpType","2");
//		List<EnScore> scoresYd = enScoreMapper.selectEnScoreByList(json).getList();
//		if(ListUtile.isEmpty(scoresYd)){
//			throw new SysException("需要先完成阅读题,才能答词汇题!");
//		}
//		json.put("problemUpType","3");
//		List<EnScore> scores = enScoreMapper.selectEnScoreByList(json).getList();
//		if(!ListUtile.isEmpty(scores)){
//			throw new SysException("当前板块本周已完成词汇题,请不要重复答题!");
//		}
//		List<EnScore> scoreList = enScoreMapper.selectEnScoreByList(JSONObject.parseObject("{\"scoreState\":\"1\",\"studentId\":\""+enStudent.getStudentId()+"\"}")).getList();
//		if(!ListUtile.isEmpty(scoreList) && (!"3".equals(scoreList.get(0).getProblemUpType()) || !scoreList.get(0).getLabelId().equals(json.getString("labelId")))){
//			throw new SysException("当前有未完成的其他练习,请先完成!");
//		}
//
//		// 如果有未答完的题目 则查询继续
//		if(!ListUtile.isEmpty(scoreList)){
//			return enAnswerMapper.selectEnAnswerByList(JSONObject.parseObject("{\"scoreId\":\""+scoreList.get(0).getScoreId()+"\"}")).getList();
//		}
//		EnScore score = new EnScore();
//		score.setScoreId(StrUtile.getId());
//		score.setScoreState("1");
//		score.setLabelId(json.getString("labelId"));
//		score.setProblemUpType("3");
//		score.setStudentId(RequestUtile.getLoginUserId());
//
//		List<EnParagraph> paragraphList = enParagraphMapper.selectEnParagraph(json);
//		List<EnAnswer> answerList = new ArrayList<>();
//		Map<String,Integer> typeTMap = new HashMap<>();
//		// 打乱顺序
//		Collections.shuffle(paragraphList);
//		for (EnParagraph h:paragraphList) {
//			// 打乱顺序
//			Collections.shuffle(h.getProblemList());
//			int s=0,d=0;
//			for (EnAnswer problem:h.getProblemList()){
//				String type = problem.getProblemType();
//				if("30240912165640980707".equals(type)){//事实题
//					s++;
//				}
//				if("30240912165640980708".equals(type)){//推断题
//					d++;
//				}
//				if(s == 3){ // 每篇抽取3道事实题
//					break;
//				}
//				if(d == 2){ // 每篇抽取2道推断题
//					break;
//				}
//				if(typeMap.containsKey(type) && typeMap.get(type) > typeTMap.getOrDefault(type,0)){
//					problem.setScoreId(score.getScoreId());
//					answerList.add(problem);
//					typeTMap.put(type,typeTMap.getOrDefault(type,0)+1);
//				}
//			}
//		}
//		if(answerList.isEmpty()){
//			throw new SysException("题库中未找到合适的试题,请联系老师!");
//		}
//		score.setProblemDate(answerList.get(0).getProblemDate());
//		enScoreMapper.insertEnScore(score);
//		enAnswerMapper.insertAllEnAnswer(answerList);
//
//		answerList = answerList.stream().sorted(Comparator.comparing(EnAnswer::getProblemId)).collect(Collectors.toList());
//		return answerList;
//	}

	/**
	 * 作文/翻译题试卷
	 */
	@Override
	public List<EnParagraph> selectEnParagraph56(JSONObject json){
		if(json.containsKey("scoreId")){
			List<EnAnswer> answerList = enAnswerMapper.selectEnAnswerByList(JSONObject.parseObject("{\"scoreId\":\""+json.getString("scoreId")+"\"}")).getList();
			Map<String,List<EnAnswer>> upType = answerList.stream().collect(Collectors.groupingBy(EnAnswer::getParagraphId));
			List<EnParagraph> paragraphList = enParagraphMapper.selectEnParagraphByList(json).getList();
			List<EnParagraph> listData = new ArrayList<>();
			for (EnParagraph h:paragraphList) {
				if(upType.containsKey(h.getParagraphId())){
					h.setProblemList(upType.get(h.getParagraphId()));
					listData.add(h);
				}
			}
			listData = listData.stream().sorted(Comparator.comparing(EnParagraph::getParagraphId)).collect(Collectors.toList());
			return listData;
		}
		json.put("problemDateThis", DateUtile.laseWook());
		EnStudent enStudent = enStudentMapper.selectEnStudentByStudentId(RequestUtile.getLoginUserId());
		if(null == enStudent){
			throw new SysException("登录账号异常,请重新登录或联系老师!");
		}
		List<EnClasssType> typeList = enClasssTypeMapper.selectEnClasssTypeByList(enStudent.getClasssId());
		Map<String,Integer> typeMap = typeList.stream().filter(t->json.getString("problemUpType").equals(t.getProblemUpType())).collect(Collectors.toMap(EnClasssType::getProblemType,EnClasssType::getProblemNum));
		if(typeMap.isEmpty()){
			switch (json.getString("problemUpType")){
				case "5":throw new SysException("当前学生不需要填写翻译题!");
				case "6":throw new SysException("当前学生不需要填写写作题!");
			}
		}
		json.put("studentId",enStudent.getStudentId());
		List<EnScore> scores = enScoreMapper.selectEnScoreByList(json).getList();
		if(!ListUtile.isEmpty(scores)){
			switch (json.getString("problemUpType")){
				case "5":throw new SysException("当前板块本周已完成翻译题,请不要重复答题!");
				case "6":throw new SysException("当前板块本周已完成写作题,请不要重复答题!");
			}
		}
		List<EnScore> scoreList = enScoreMapper.selectEnScoreByList(JSONObject.parseObject("{\"scoreState\":\"1\",\"studentId\":\""+enStudent.getStudentId()+"\"}")).getList();
		if(!ListUtile.isEmpty(scoreList) && (!json.getString("problemUpType").equals(scoreList.get(0).getProblemUpType()) || !scoreList.get(0).getLabelId().equals(json.getString("labelId")))){
			throw new SysException("当前有未完成的其他练习,请先完成!");
		}

		// 如果有未答完的题目 则查询继续
		if(!ListUtile.isEmpty(scoreList)){
			List<EnAnswer> answerList = enAnswerMapper.selectEnAnswerByList(JSONObject.parseObject("{\"scoreId\":\""+scoreList.get(0).getScoreId()+"\"}")).getList();
			Map<String,List<EnAnswer>> upType = answerList.stream().collect(Collectors.groupingBy(EnAnswer::getParagraphId));
			JSONObject da = new JSONObject();
			da.put("problemDate",scoreList.get(0).getProblemDate());
			List<EnParagraph> paragraphList = enParagraphMapper.selectEnParagraphByList(da).getList();
			List<EnParagraph> listData = new ArrayList<>();
			for (EnParagraph h:paragraphList) {
				if(upType.containsKey(h.getParagraphId())){
					h.setProblemList(upType.get(h.getParagraphId()));
					listData.add(h);
				}
			}
			listData = listData.stream().sorted(Comparator.comparing(EnParagraph::getParagraphId)).collect(Collectors.toList());
			return listData;
		}
		EnScore score = new EnScore();
		score.setScoreId(StrUtile.getId());
		score.setScoreState("1");
		score.setLabelId(json.getString("labelId"));
		score.setProblemUpType(json.getString("problemUpType"));
		score.setStudentId(RequestUtile.getLoginUserId());

		List<EnAnswer> answerList = new ArrayList<>();
		Map<String,Integer> typeTMap = new HashMap<>();
		List<EnProblem> listProblem = enProblemAnswerMapper.selectEnProblemAnswerByList(json).getList();
		Map<String,List<EnProblem>> hearingMap = listProblem.stream().collect(Collectors.groupingBy(EnProblem::getParagraphId));
		List<EnParagraph> paragraphList = enParagraphMapper.selectEnParagraphByList(json).getList();
		List<EnParagraph> listData = new ArrayList<>();
		// 打乱顺序
		Collections.shuffle(paragraphList);
		for (EnParagraph h:paragraphList) {
			h.setProblemList(new ArrayList<>());
			if(hearingMap.containsKey(h.getParagraphId())){
				List<EnProblem> problemList = hearingMap.get(h.getParagraphId());
				// 打乱顺序
				Collections.shuffle(problemList);
				for (EnProblem problem:problemList){
					String type = problem.getProblemType();
					if(typeMap.containsKey(type) && typeMap.get(type) > typeTMap.getOrDefault(type,0)){
						EnAnswer answer = JSONObject.parseObject(JSONObject.toJSONString(problem),EnAnswer.class);
						answer.setScoreId(score.getScoreId());
						answerList.add(answer);
						h.getProblemList().add(answer);
						typeTMap.put(type,typeTMap.getOrDefault(type,0)+1);
					}
				}
				if(!h.getProblemList().isEmpty()){
					h.setProblemList(h.getProblemList().stream().sorted(Comparator.comparing(EnAnswer::getProblemId)).collect(Collectors.toList()));
					listData.add(h);
				}
			}
		}
		if(answerList.isEmpty()){
			throw new SysException("题库中未找到合适的试题,请联系老师!");
		}
		score.setProblemDate(answerList.get(0).getProblemDate());
		enScoreMapper.insertEnScore(score);
		enAnswerMapper.insertAllEnAnswer(answerList);

		listData = listData.stream().sorted(Comparator.comparing(EnParagraph::getParagraphId)).collect(Collectors.toList());
		return listData;
	}

	/**
	 * 阅读题试卷
	 */
	@Override
	public List<EnParagraph> selectEnParagraph(JSONObject json){
		if(json.containsKey("scoreId")){
			List<EnAnswer> answerList = enAnswerMapper.selectEnAnswerByList(JSONObject.parseObject("{\"scoreId\":\""+json.getString("scoreId")+"\"}")).getList();
			List<EnParagraph> list = enParagraphMapper.selectEnParagraphByList(json).getList();
			Map<String,List<EnAnswer>> upType = answerList.stream().collect(Collectors.groupingBy(EnAnswer::getParagraphId));
			List<EnParagraph> oo = new ArrayList<>();
			for (EnParagraph p:list) {
				if(upType.containsKey(p.getParagraphId())){
					p.setProblemList(upType.get(p.getParagraphId()));
					oo.add(p);
				}
			}
			oo = oo.stream().sorted(Comparator.comparing(EnParagraph::getParagraphSection)).collect(Collectors.toList());
			return oo;
		}
		json.put("problemDateThis",DateUtile.laseWook());
		json.put("problemUpType","2");
		EnStudent enStudent = enStudentMapper.selectEnStudentByStudentId(RequestUtile.getLoginUserId());
		if(null == enStudent){
			throw new SysException("登录账号异常,请重新登录或联系老师!");
		}
		json.put("studentId",enStudent.getStudentId());
		List<EnClasssType> typeList = enClasssTypeMapper.selectEnClasssTypeByList(enStudent.getClasssId());
		Map<String,Integer> typeMap = typeList.stream().filter(t->"2".equals(t.getProblemUpType())).collect(Collectors.toMap(EnClasssType::getProblemType,EnClasssType::getProblemNum));
		if(typeMap.isEmpty()){
			throw new SysException("当前学生不需要填写解答题!");
		}
		List<EnScore> scores = enScoreMapper.selectEnScoreByList(json).getList();
		if(!ListUtile.isEmpty(scores)){
			throw new SysException("当前板块本周已完成阅读题,请不要重复答题!");
		}
		List<EnScore> scoreList = enScoreMapper.selectEnScoreByList(JSONObject.parseObject("{\"scoreState\":\"1\",\"studentId\":\""+enStudent.getStudentId()+"\"}")).getList();
		if(!ListUtile.isEmpty(scoreList) && (!"2".equals(scoreList.get(0).getProblemUpType()) || !scoreList.get(0).getLabelId().equals(json.getString("labelId")))){
			throw new SysException("当前有未完成的其他练习,请先完成!");
		}

		// 如果有未答完的题目 则查询继续
		if(!ListUtile.isEmpty(scoreList)){
			List<EnAnswer> answerList = enAnswerMapper.selectEnAnswerByList(JSONObject.parseObject("{\"scoreId\":\""+scoreList.get(0).getScoreId()+"\"}")).getList();
			JSONObject da = new JSONObject();
			da.put("problemDate",scoreList.get(0).getProblemDate());
			List<EnParagraph> list = enParagraphMapper.selectEnParagraphByList(da).getList();
			Map<String,List<EnAnswer>> upType = answerList.stream().collect(Collectors.groupingBy(EnAnswer::getParagraphId));
			List<EnParagraph> oo = new ArrayList<>();
			for (EnParagraph p:list) {
				if(upType.containsKey(p.getParagraphId())){
					p.setProblemList(upType.get(p.getParagraphId()));
					oo.add(p);
				}
			}
			oo = oo.stream().sorted(Comparator.comparing(EnParagraph::getParagraphSection)).collect(Collectors.toList());
			return oo;
		}
		EnScore score = new EnScore();
		score.setScoreId(StrUtile.getId());
		score.setScoreState("1");
		score.setLabelId(json.getString("labelId"));
		score.setProblemUpType("2");
		score.setStudentId(RequestUtile.getLoginUserId());

		List<EnAnswer> answerList = new ArrayList<>();
		Map<String,Integer> typeTMap = new HashMap<>();
		List<EnParagraph> list = enParagraphMapper.selectEnParagraphByList(json).getList();
		// 打乱顺序
		List<EnParagraph> list1 = enParagraphMapper.selectEnParagraph(json);
		Map<String,List<EnAnswer>> pmap = list1.stream().filter(p->!ListUtile.isEmpty(p.getProblemList())).collect(Collectors.toMap(EnParagraph::getParagraphId,EnParagraph::getProblemList));
		Map<String,List<EnParagraph>> lmap = list.stream().collect(Collectors.groupingBy(EnParagraph::getParagraphSection));
		List<EnParagraph> oo = new ArrayList<>();
		for (Map.Entry<String,List<EnParagraph>> le:lmap.entrySet()){
			List<EnParagraph> ps = le.getValue();
			Collections.shuffle(ps);
			List<EnAnswer> laa = null;
			for (EnParagraph p:ps) {
				if (pmap.containsKey(p.getParagraphId())) {
					laa = pmap.get(p.getParagraphId());
					oo.add(p);
					break;
				}
			}
			// 如果没有试题 则报错
			if(ListUtile.isEmpty(laa)){
				throw new SysException("题库中未找到合适的试题,请联系老师!");
			}
			// 15道词汇题
			if(!le.getKey().contains("A")) {
				List<EnAnswer> lac = laa.stream().filter(a -> "40240912165652307424".equals(a.getProblemType())).collect(Collectors.toList());
				for (int i = 0; i < lac.size() && i < 15; i++) {
					lac.get(i).setScoreId(score.getScoreId());
					answerList.add(lac.get(i));
				}
			}
			List<EnAnswer> la = laa.stream().filter(a-> !"40240912165652307424".equals(a.getProblemType())).collect(Collectors.toList());
			if(le.getKey().contains("A") || le.getKey().contains("B")){
				for (int i = 0; i < la.size() && i< 10; i++) {
					la.get(i).setScoreId(score.getScoreId());
					answerList.add(la.get(i));

				}
			}
			if(le.getKey().contains("C") || le.getKey().contains("D")){
				//打乱顺序
				Collections.shuffle(la);
				int s=0,d=0;
                for (EnAnswer answer : la) {
                    String type = answer.getProblemType();
                    if ("30240912165640980707".equals(type)) {//事实题
                        if (s < 3) {
                            answer.setScoreId(score.getScoreId());
                            answerList.add(answer);
							s++;
                        }
                        continue;
                    }
                    if ("30240912165640980708".equals(type)) {//推断题
                        if (d < 2) {
                            answer.setScoreId(score.getScoreId());
                            answerList.add(answer);
                            d++;
                        }
                    }
                }
			}
		}
		if(answerList.isEmpty()){
			throw new SysException("题库中未找到合适的试题,请联系老师!");
		}
		if(answerList.size() < 75){
			throw new SysException("题库中试题数量不足,请联系老师!");
		}
		score.setProblemDate(answerList.get(0).getProblemDate());
		enScoreMapper.insertEnScore(score);
		enAnswerMapper.insertAllEnAnswer(answerList);
		answerList = answerList.stream().sorted(Comparator.comparing(EnAnswer::getProblemId)).collect(Collectors.toList());
		Map<String,List<EnAnswer>> upType = answerList.stream().collect(Collectors.groupingBy(EnAnswer::getParagraphId));
		for (EnParagraph p:oo) {
			p.setProblemList(upType.get(p.getParagraphId()));
		}
		oo = oo.stream().sorted(Comparator.comparing(EnParagraph::getParagraphSection)).collect(Collectors.toList());
		return oo;
	}

}